<template>
  <div>
    <!-- 实销信息查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="qjhSalesQuery"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchDealer :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>

    <Drawer :visible.sync="visible" :title="drawerTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :type="handleType" :rowData="formData" @close="emitCloseHandler" />
    </Drawer>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList, exportExcel, exporturl } from '@/api/omSale/ActualSales/SalesQuery';
import SonModel from './SonModel';
import SearchDealer from './SearchDealer';
import { vehicleConfiguration, getRegion, getCommunity } from '@/api/omFinance';
import { exportFile } from '@/utils/index';

export default {
  name: 'SalesQuery',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      exportLoading: false,
      visible: false,
      isDealer: false,
      handleType: '',
      drawerTitle: ''
    };
  },
  components: {
    SonModel,
    SearchDealer
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    // this.getList();
    // this.getDeptData();
    // this.queryYearInfo();
  },
  methods: {
    // 获取当前年月日跟上年年份
    queryYearInfo() {
      let date = new Date();
      let thisYear = date.getFullYear();
      let thisMonth = date.getMonth() + 1;
      if (thisMonth == 13) {
        thisMonth = 1;
        thisYear = thisYear + 1;
      }

      debugger;
      let stDate = date.getFullYear() + '-' + thisMonth + '-01';
      let endDate = thisYear + '-' + thisMonth + '-' + date.getDate();
      let dateValue = [stDate, endDate];
      this.topFilterList.find(item => item.fieldName === 'checkDateStart|checkDateEnd').initialValue = dateValue;
    },
    async getList() {
      let res = await vehicleConfiguration(0, { isUnlimited: 10041001 });
      this.topFilterList.find(item => item.fieldName === 'vehicleInfo').itemList = res.data;
    },
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName == 'deptId').itemList = res.data.map(x => ({ text: x.orgName, value: x.id }));
      }
    },
    //加载办事处数据
    async getOfficeData(officeId) {
      const res = await getCommunity(officeId);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName == 'officeId').itemList = res.data.map(x => ({ text: x.orgName, value: x.id }));
      }
    },
    // 导出
    async exportHandle() {
      // let json = Object.assign({}, { CODE: 'CODE_0000007' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          exportExcel(this.fetchParams)
            .then(response => {
              debugger;
              if (response.headers.code == '500') {
                this.$notify.error({ title: '提示信息', message: '数据已超过20000，无法导出，请分批次导出数据' });
              } else {
                exportFile(response.data, '实销信息查询', 'xls');
              }
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },

    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    seacherFun() {
      this.isDealer = true;
    },
    // 明细
    detailHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    // 删除
    delHandle() {},
    showHandler() {
      this.drawerTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    emitCloseHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    emitCloseHandler1(val, data) {
      this.isDealer = val;
      let dealerCodes = [];
      let dealerNames = [];
      data.map(x => {
        dealerCodes.push(x.dealerCode);
        dealerNames.push(x.dealerName);
      });
      this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
    },
    changeHandle(params) {
      // let vin = params.vin;
      let checkDateStart = params.checkDateStart;
      let checkDateEnd = params.checkDateEnd;
      // if (vin == null && checkDateStart == null && checkDateEnd == null) {
      //   this.$notify.error({ title: '提示信息', message: '您好，请您至少填加VIN或者实销通过日期任意一个条件，添加后再次查询。' });
      //   return;
      // }

      var dateBegin = new Date(checkDateStart);
      var dateEnd = new Date(checkDateEnd);
      var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
      var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
      if (dayDiff > 732) {
        this.$notify.error({ title: '提示信息', message: '您好，实销通过日期请不要超过两年。' });
        return;
      }

      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    createdFrom() {
      return [
        {
          type: 'TEXT_AREA',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '多个经销商时,请用逗号分隔',
          maxlength: '',
          maxRows: 2
        },
        {
          type: 'TEXT_AREA',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '多个vin时,请用换行分隔',
          maxlength: '',
          maxRows: 2
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '零售订单号',
          fieldName: 'soNo',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        // {
        //   type: 'SELECT',
        //   label: '溯源平台上报状态',
        //   fieldName: 'platformReportedStatus',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('')
        // },
        // {
        //   type: 'SELECT',
        //   label: '是否更新',
        //   fieldName: 'isUpdate',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('1004')
        // },
        {
          type: 'SELECT',
          label: '审核状态',
          fieldName: 'licenseplateReportStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2427')
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          // 审核，不是等于24271002的时候，都不能点
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row)} disabled={props.row.licenseplateReportStatus !== '24271002' ? true : false}>
                  审核
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        // {
        //   title: '溯源平台上报状态',
        //   dataIndex: 'platformReportedStatus',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '溯源平台首次上报日期',
        //   dataIndex: 'platformReportedDate',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '是否更新',
        //   dataIndex: 'isUpdate',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '审核时间',
          dataIndex: 'auditDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '审核人',
          dataIndex: 'auditBy',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '实销更新日期',
        //   dataIndex: 'isUpdateDate',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   dateFormat: 'yyyy-MM-dd'
        // },
        {
          title: '实销建档日期',
          dataIndex: 'createdDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '审核状态',
          dataIndex: 'licenseplateReportStatus', // TODO 1523
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2427'),
          render: props => {
            return <span>{this.createDictText(props.row.licenseplateReportStatus, '2427')}</span>;
          }
        },
        {
          title: '车牌上报日期',
          dataIndex: 'licenseplateReportTime',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '零售单号',
          dataIndex: 'soNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          align: 'center',
          width: 180,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户编号',
          dataIndex: 'potentialCustomerNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType', // TODO 1523
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2428'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '2428')}</span>;
          }
        },
        {
          title: '使用人',
          dataIndex: 'user',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '使用人电话',
          dataIndex: 'userMobile',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          align: 'center',
          width: 250,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '公告号',
          dataIndex: 'announcementNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库日期',
          dataIndex: 'latestStockOutDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '配车日期',
          dataIndex: 'dispatchedData',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '开票日期',
          dataIndex: 'drawTime',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '市场指导价',
          dataIndex: 'directivePrice',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2
        },
        {
          title: '发动机',
          dataIndex: 'engineNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '电机号',
          dataIndex: 'eleEngineNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '电池号',
          dataIndex: 'batteryNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '上牌省份',
          dataIndex: 'licensePlateProvinceName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '上牌城市',
          dataIndex: 'licensePlateCityName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车牌号',
          dataIndex: 'licensePlateNumber',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车辆性质',
          dataIndex: 'licenseVehicleNature',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2425'),
          render: props => {
            return <span>{this.createDictText(props.row.licenseVehicleNature, '2425')}</span>;
          }
        },
        {
          title: '是否大客户',
          dataIndex: 'isVip',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isVip, '1004')}</span>;
          }
        },
        // {
        //   title: '是否特殊订单',
        //   dataIndex: 'isSpecialOrder',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1004'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.isSpecialOrder, '1004')}</span>;
        //   }
        // }
        // {
        //   title: '订单类型',
        //   dataIndex: 'orderType', // TODO 6026
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('6026'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.orderType, '6026')}</span>;
        //   }
        // },
      ];
    }
  }
};
</script>
